package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/8 13:37
 */
public class Title707II {

    /**
     * 双向循环表
     */
    class ListNode {
        int val;

        ListNode prev;

        ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }
    }

    ListNode head;

    ListNode tail;

    int size;

    public Title707II() {
        //带头尾结点的双链表
        head = new ListNode(0);
        tail = new ListNode(0);
        head.next = tail;
        tail.prev = head;
        size = 0;
    }

    /**
     * 获取链表中第 index 个节点的值。如果索引无效，则返回-1。
     * @param index
     * @return
     */
    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        ListNode cur;
        //判断第index节点距离哪端比较近
        if (index < (size - 1) / 2) {
            //从头开始遍历
            cur = head;
            for (int i = 0; i <= index; i++) {
                cur = cur.next;
            }
        } else {
            //从tail倒着开始遍历
            cur = tail;
            for (int i = 0; i <= size - 1 - index; i++) {
                cur = cur.prev;
            }
        }
        return cur.val;
    }

    /**
     * 在链表的第一个元素之前添加一个值为 val 的节点。插入后，新节点将成为链表的第一个节点。
     * @param val
     */
    public void addAtHead(int val) {
        ListNode cur = head;
        ListNode node = new ListNode(val);
        node.next = cur.next;
        cur.next.prev = node;
        cur.next = node;
        node.prev = cur;
        size++;
    }

    public void addAtTail(int val) {
        ListNode cur = tail;
        ListNode node = new ListNode(val);
        node.prev = cur.prev;
        node.next = cur;
        cur.prev = node;
        node.prev.next = node;
        size++;
    }

    /**
     * 在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度，
     * 则该节点将附加到链表的末尾。如果 index 大于链表长度，则不会插入节点。如果index小于0，则在头部插入节点。
     * @param index
     * @param val
     */
    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        if (index < 0) {
            index = 0;
        }
        ListNode cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        ListNode node = new ListNode(val);
        node.next = cur.next;
        cur.next.prev = node;
        cur.next = node;
        node.prev = cur;
        size++;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        ListNode cur = head;
        for (int i = 0; i < index; i++) {
            cur = cur.next;
        }
        ListNode node = cur.next.next;
        cur.next = node;
        node.prev = cur;
        size--;
    }

    public static void main(String[] args) {
        Title707II head = new Title707II();
        head.addAtHead(1);
        head.addAtTail(3);
        head.addAtIndex(1, 2);
        head.get(1);
        head.deleteAtIndex(1);
        head.get(1);
    }
}
